package com.aqiang.lib_core.mvp

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.View.NO_ID
import android.view.ViewGroup
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext

abstract class BaseFragment<P> : Fragment(), CoroutineScope {
    protected var mPresenter:P? = null
    private lateinit var job: Job
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(bindLayout(),container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        createPresenter()
        job = Job()
        initView(savedInstanceState)
        initData()
        initEvent()
    }

    override val coroutineContext: CoroutineContext
        get() = job + Dispatchers.Main

    protected fun <T : View> findViewById(id:Int):T{
        return view!!.findViewById<T>(id)
    }

    protected fun doAsynTask(doSome:()->Unit){
        launch {
            withContext(Dispatchers.IO){
                doSome()
            }
        }
    }

    protected fun <T> doUiThread(r: Deferred<T>, doSome:(r:T)->Unit){
        GlobalScope.launch {
            withContext(Dispatchers.Main){
                doSome(r.await())
            }
        }
    }

    abstract fun bindLayout(): Int

    abstract fun createPresenter()

    abstract fun initView(savedInstanceState: Bundle?)

    abstract fun initData()

    abstract fun initEvent()

    override fun onDestroy() {
        super.onDestroy()
        if(mPresenter != null){
            mPresenter = null
        }
        if(job != null){
            job.cancel()
        }
    }
}